//
//  ST_PersonalFeedController.swift
//  btvideo
//
//  Created by mac on 2020/9/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyAttributes
import SwiftyUserDefaults

class ST_PersonalFeedController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight + 54, left: 0, bottom: 0, right: 0))
        }
        
        scrollView.addSubview(root_view)
        
        let h = ScreenHeight - statusBarHeight - 54
        
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(ScreenWidth*2)
            make.height.equalTo(h)
        }
        
        self.addChild(recommend_controller)
        self.addChild(nearby_controller)
        
        
        
        root_view.addSubview(recommend_controller.view)
        root_view.addSubview(nearby_controller.view)
        
        
        
        recommend_controller.view.snp.makeConstraints { (make) in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(h)
            make.top.bottom.left.equalToSuperview()
        }
        
        nearby_controller.view.snp.makeConstraints { (make) in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(h)
            make.top.bottom.right.equalToSuperview()
            make.left.equalTo(recommend_controller.view.snp.right)
        }
        
        
        
        self.view.addSubview(recommend_btn)
        self.view.addSubview(attract_btn)
        
        
        let relativeOffset = 10/375*ScreenWidth
        
        recommend_btn.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(38)
            make.top.equalToSuperview().offset(statusBarHeight+3)
            make.right.equalTo(self.view.snp.centerX).offset(-relativeOffset)
        }
        
        attract_btn.snp.makeConstraints { (make) in
            make.size.top.equalTo(recommend_btn)
            make.left.equalTo(self.view.snp.centerX).offset(relativeOffset)
        }
        
        layout_others_widget()
        
        binding()
        
        NotificationCenter.default.addObserver(self, selector: #selector(member_status_observer), name: Notification.Name.in_pur_status_success, object: nil)
        
    }
    
    
    private func binding(){
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            
            if f == true,ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female && Defaults[.isPanda] == false && !ST_SwiftConst.shared.hidden_home_trophy{

                own.view.addSubview(own.trophy_btn)
                own.trophy_btn.snp.makeConstraints { (make) in
                    make.width.height.equalTo(30)
                    make.right.equalTo(own.add_btn.snp.left)
                    make.centerY.equalTo(own.add_btn)
                }
                
            }else{
                
                own.trophy_btn.removeFromSuperview()
            }
            
        }).disposed(by: rx.disposeBag)
            
    }
    
    @objc func layout_others_widget(){
        
        recommend_controller.refresh_header_layout()
        
        other_wdiget_controls.forEach({  $0.removeFromSuperview() })
        
        other_wdiget_controls = [filter_btn,sign_label,add_btn]
        
        other_wdiget_controls.forEach({ view.addSubview($0) })
        
        
        filter_btn.snp.makeConstraints { (make) in
            make.height.width.equalTo(44)
            make.left.equalToSuperview().offset(8)
            make.centerY.equalTo(recommend_btn)
        }
        
        
        sign_label.snp.makeConstraints { (make) in
            make.right.top.equalTo(attract_btn)
            make.width.equalTo(29)
            make.height.equalTo(16)
        }
        
        let offset:CGFloat = (44-30)/2.0
        
        
        add_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.right.equalToSuperview().offset(-15+offset)
            make.top.equalToSuperview().offset(statusBarHeight+7-offset)
        }
        
    }
    
    
    @objc fileprivate func member_status_observer(){
        
    }
    
    //    MARK: - Properties
    
    fileprivate lazy var recommend_controller = ST_RecommendForYouController()
    
    
    fileprivate lazy var nearby_controller = ST_NearbyForYouViewController()
    
    
    
    fileprivate lazy var btn_selected_image:UIImage = {
        let img = UIImage.init(color: UIColor.init(hexString: "#FEC207")!, size: CGSize.init(width: 1, height: 1))
        return img
    }()
    
    fileprivate lazy var btn_normal_image:UIImage = {
        let img = UIImage.init(color: UIColor.white, size: CGSize.init(width: 1, height: 1))
        return img
    }()
    
    fileprivate lazy var last_btn = recommend_btn
    
    fileprivate var baseTag = 10234
    
    fileprivate lazy var recommend_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setBackgroundImage(btn_selected_image, for: UIControl.State.selected)
        control.setBackgroundImage(btn_normal_image, for: UIControl.State.normal)
        control.isSelected = true
        control.cornerRadius = 19
        control.setTitleForAllStates("为你推荐")
        control.tag = baseTag
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.addTarget(self, action: #selector(click_switch_controller_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var attract_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setBackgroundImage(btn_selected_image, for: UIControl.State.selected)
        control.setBackgroundImage(btn_normal_image, for: UIControl.State.normal)
        control.cornerRadius = 19
        
        control.setTitleForAllStates("附近在线")
        control.tag = baseTag + 1
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.addTarget(self, action: #selector(click_switch_controller_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var add_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_添加")!)
        control.addTarget(self, action: #selector(push_peculiarity(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var trophy_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_trophy")!)
        control.addTarget(self, action: #selector(push_trophy(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var scrollView:UIScrollView = {
        let control = UIScrollView()
        control.backgroundColor = UIColor.white
        control.isScrollEnabled = false
        control.isPagingEnabled = true
        control.delegate = self
        return control
    }()
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate var other_wdiget_controls = Array<UIView>()
    
    
    fileprivate lazy var filter_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_筛选_ai_recommend")!)
        
        control.addTarget(self, action: #selector(option_handle), for: UIControl.Event.touchUpInside)
        
        control.addSubview(filter_round_sign_view)
        
        filter_round_sign_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(8)
            make.top.equalToSuperview().offset(9)
            make.right.equalToSuperview().offset(-9)
        }
        
        return control
    }()
    
    fileprivate lazy var filter_round_sign_view:UIView = {
        
        let control = UIView()
        
        control.backgroundColor = UIColor.init(hex: 0xFF5959)
        
        control.cornerRadius = 8/2.0
        
        return control
    }()
    
    
    
    fileprivate lazy var sign_label:UILabel = {
        let control = UILabel()
        control.text = "NEW"
        control.font = UIFont.systemFont(ofSize: 9, weight: UIFont.Weight.medium)
        control.textColor = .white
        control.textAlignment = .center
        control.backgroundColor = UIColor.init(hex: 0xEB3C3C)
        control.alpha = 1
        control.cornerRadius = 8
        return control
    }()
    
    
    fileprivate var curr_filter = ST_PairsLoveFilterModel()
    
}

extension ST_PersonalFeedController{
    
    @objc fileprivate func option_handle(){
        
        filter_round_sign_view.isHidden = true
        
        let vc = ST_OptionPopoverViewController()
        vc.search_closure = {
            
            ST_BTUserInfoManager.shared.judge_account_frozen().subscribe(onNext: {
            
                GlobalPresent(toController: UINavigationController.create_hiding_bar_navigation_controller(rootViewController: ST_AIRecommendSearchController()), animated: false)
                
            }).disposed(by: self.rx.disposeBag)
            
        }
        
        vc.setting_click_closure = {[weak self] in
            
            self?.recommend_controller.filter_handle()
        }
        
        
        vc.overCurrentContext = true
        
        vc.over_current_context_alpha = "0.1"
        
        GlobalPresent(toController: vc, animated: false)
    }
    
    
    
    fileprivate func authorization_location_tips_handle(){
        
        
        let titleStr = "需要开启定位权限".withAttributes([Attribute.textColor(Color.init(red: 51, green: 51, blue: 51)!),Attribute.font(Font.systemFont(ofSize: 18, weight: UIFont.Weight.medium))])
        
        
        let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.lineSpacing = 5
        
        let content_string = "通话需要访问你的定位\n立即前往开启？".withAttributes([Attribute.textColor(Color.init(red: 97, green: 102, blue: 111)!),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.regular)),Attribute.paragraphStyle(style)])
        
        let alert = ST_BTAlertViewController.init(title: titleStr, message: content_string, imageName: "首页_icon_提示",cancelText:"稍后再说")
        
        alert.root_view_height = 290;
        
        alert.overCurrentContext = true;
        
        alert.confirm_closure = {
            
            PushTianSetting()
        }
        
        GlobalPresent(toController: alert)
        
    }
}

//MARK: - Method
extension ST_PersonalFeedController:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let  page = (scrollView.contentOffset.x + (0.5 * ScreenWidth)) / ScreenWidth
        
        if  page.int == 0{
            click_switch_controller_handle(sender: self.recommend_btn)
        }else {
            click_switch_controller_handle(sender: self.attract_btn)
        }
    }
    @objc func push_trophy(sender:UIButton){
        
        
        self.navigationController?.pushViewController(ST_RankWebViewController())
        
        
        
        //        self.navigationController?.pushViewController(ST_TrophyViewController())
    }
    
    @objc func push_peculiarity(sender:UIButton){
        /* 取消发布日常
         let alert = ST_PushOptionViewController()
         
         alert.overCurrentContext = true
         
         alert.over_current_context_alpha = "0.4"
         
         GlobalPresent(toController: alert)
         */
        
        push_to_push_peculiarity_controller(navigationController: ST_BTLaunchController.shared.navigationController)
        
        
        
    }
    
    @objc func click_switch_controller_handle(sender:UIButton){
        
        if sender.isSelected{
            return
        }
        
        if sender == attract_btn{
            
            sign_label.alpha = 0
            
        }else{
        }
        
        last_btn.isSelected = false
        
        sender.isSelected = true
        
        last_btn = sender
        
        filter_btn.alpha = sender == recommend_btn ? 1 : 0
        
        scrollView.setContentOffset(CGPoint.init(x: (sender.tag-self.baseTag).cgFloat*ScreenWidth, y: 0), animated: true)
        
    }
    
}


extension ST_PersonalFeedController{
    
    func scroll_to_tab(index:Int){
        
        guard let btn = [recommend_btn,attract_btn][safe:index] else{
            return
        }
        
        click_switch_controller_handle(sender: btn)
        
    }
    
}
